#include "callout.h"
#include <QtGui/QPen>
#include <QtGui/QPainter>
#include <QtGui/QFontMetrics>
#include <QtCharts/QChart>

CallOut::CallOut(QChart *chart):
    QGraphicsItem(chart)
{
    m_chart = chart;
}

//void CallOut::setText(const QString &text)
//{
//    m_text = text;
//    QFontMetrics metrics(m_font);
//    m_textRect = metrics.boundingRect(QRect(0, 0, 150, 150), Qt::AlignLeft, m_text);
//    m_textRect.translate(5, 5);
//    prepareGeometryChange();
//    m_rect = m_textRect.adjusted(-5, -5, 5, 5);
//}

void CallOut::setAnchor(QPointF point)
{
    m_anchor = point;
}

void CallOut::updateGeometry()
{
    prepareGeometryChange();
    setPos(m_chart->rect().topLeft());
}

QRectF CallOut::boundingRect() const
{
    //QPointF anchor = mapFromParent(m_chart->mapToPosition(m_anchor));
    return m_chart->rect();
}

void CallOut::paint(QPainter *painter, const QStyleOptionGraphicsItem *option,QWidget *widget)
{
    Q_UNUSED(option)
    Q_UNUSED(widget)

    QPen pen;
    pen.setWidth(0);
    pen.setStyle(Qt::DashLine);
    pen.setColor(Qt::red);
    painter->setPen(pen);

    QPointF pos = m_chart->mapToPosition(m_anchor);
    QPointF origin = m_chart->plotArea().bottomLeft();
    QPointF rightTopP = m_chart->plotArea().topRight();
    QPointF lineP11 =QPointF(pos.x(),origin.y());
    QPointF lineP12= QPointF(pos.x(),rightTopP.y());
    QPointF lineP21 =QPoint(origin.x(),pos.y());
    QPointF lineP22 = QPointF(rightTopP.x(),pos.y());

    painter->drawLine(lineP11,lineP12);
    painter->drawLine(lineP21,lineP22);

    painter->drawText(pos.x()+5,pos.y()-5,QString("X: %1 \nY: %2 ").arg(m_anchor.x(),2).arg(m_anchor.y(),2));
}
